package com.blackhorse.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 */
public class SysExceptionResolver implements HandlerExceptionResolver {
    /**
     * 处理异常逻辑
     *
     * @param request  请求
     * @param response 响应
     * @param handler  异常处理器对象
     * @param ex       处理的异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        //1.获取异常对象
        SysException e = null;
        if (ex instanceof SysException) {
            e = (SysException) ex;//如果是SysException就显示原本异常信息
        } else {
            e = new SysException("系统正在维护...");//如果不是SysException就显示"系统正在维护"
        }
        //2.创建ModelAndView对象
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMsg", e.getMessage());
        mav.setViewName("error");
        //3.转发至异常页面
        return mav;
    }
}
